/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package tletlis.controller;

import java.awt.Component;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import tletlis.model.Area.BrickEvent;

/**
 * A class keeping track of key events.
 * @author Gustav
 */
public class Keys implements KeyListener, Runnable {

    private Controller controller;

    private boolean down = false;
    private boolean right = false;
    private boolean left = false;

  /**
   * The Keys constructor that add key listeners to the GUI so the game
   * can notice rotations and movements.
   * @param comp The components listening for key events
   * @param control The controller that has the update game method.
   */
    public Keys(List<Component> comp, Controller control) {
        for(Component c: comp) {
            c.addKeyListener(this);
        }
        controller = control;
        new Thread(this).start();
    }

    public void run() {
        while(true) {
            if(right && !left)
                controller.GameUpdate(BrickEvent.RIGHT);
            else if(left && !right)
                controller.GameUpdate(BrickEvent.LEFT);
            if(down) {
                controller.GameUpdate(BrickEvent.DOWN);
            }
            try {
                Thread.sleep(100);
            }catch(InterruptedException ie){}
        }
    }
    
    public void keyTyped(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
            controller.GameUpdate(BrickEvent.RIGHT);
        }
        else if(e.getKeyCode() == KeyEvent.VK_LEFT) {
            controller.GameUpdate(BrickEvent.LEFT);
        }
        else if(e.getKeyCode() == KeyEvent.VK_DOWN) {
            controller.GameUpdate(BrickEvent.DOWN);
        }
        else if(e.getKeyCode() == KeyEvent.VK_SPACE) {
            controller.GameUpdate(BrickEvent.ALLDOWN);
        }
        else if(e.getKeyCode() == KeyEvent.VK_D) {
            controller.GameUpdate(BrickEvent.ROTATE);
            
        }
        
    }

    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_RIGHT)
            right = true;
        else if(e.getKeyCode() == KeyEvent.VK_LEFT)
            left = true;
        else if(e.getKeyCode() == KeyEvent.VK_DOWN)
            down = true;
        else if(e.isShiftDown()) {
            controller.GameUpdate(BrickEvent.ROTATE);
        }
        else if(e.getKeyCode() == KeyEvent.VK_SPACE) {
            
            controller.GameUpdate(BrickEvent.ALLDOWN);
        }
        
    }

    public void keyReleased(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_RIGHT)
            right = false;
        else if(e.getKeyCode() == KeyEvent.VK_LEFT)
            left = false;
        else if(e.getKeyCode() == KeyEvent.VK_DOWN)
            down = false;
    }

}
